package com.apex.wx.controller;

import com.apex.security.api.entity.TBsdtWxUser;
import com.apex.wx.service.AccessTokenService;
import com.apex.wx.service.WxLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Create by IntelliJ IDEA
 * 用户：王建
 * 日期：2018-4-8
 */
@Controller
public class UserLoginController {

    @Value("${weix.open:false}")
    private boolean isOpenWeiXin;

    @Value("${weix.appid:111}")
    private String appId;

    @Value("${weix.secret:11}")
    private String WSecret;

    @Autowired
    private WxLoginService service;

    @Autowired
    private AccessTokenService accessTokenService;

    @RequestMapping("/")
    public String index() {
        return "redirect:/uc/schedule/index";
    }

    @RequestMapping("/index")
    public String index(HttpServletRequest request, ModelMap modelMap) {
        return "redirect:/uc/schedule/index";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpSessionRequestCache sessionRequestCache,
                        HttpServletResponse response, ModelMap modelMap) {
        String code = request.getParameter("code");
        String redirectUrl = "/uc/schedule/index";
        SavedRequest savedRequest = sessionRequestCache.getRequest(request, response);
        if (null != savedRequest) {
            redirectUrl = savedRequest.getRedirectUrl();
        }
        if (redirectUrl.indexOf("/login") != -1) {
            return "redirect:/index";
        }
        String userAgent = request.getHeader("user-agent");
        if (StringUtils.isEmpty(userAgent)) {
            userAgent = "none";
        }
        if (isOpenWeiXin && userAgent.indexOf("micromessenger") != -1) {//开启了微信公众号并且不是pc端访问
            if (service.checkedWeixinLogin(request, response)) {
                return "redirect:" + redirectUrl;
            }
            TBsdtWxUser user = null;
            if (StringUtils.isEmpty(code)) {
                StringBuffer url = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?");
                url.append("appid=" +appId);
                try {
                    url.append("&redirect_uri=" + URLEncoder.encode(redirectUrl, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                url.append("&response_type=code&scope=snsapi_userinfo#wechat_redirect");
                return "redirect:" + url.toString();
            }
            String openId=accessTokenService.getOpenId(appId,code,WSecret);
            modelMap.put("openId",openId);

        }
        if (service.checkedLogin(request, response)) {
            return "redirect:" + redirectUrl;
        }
        return "mobile/login/index";
    }

}
